// import CryptoJS from 'crypto-js'
export const fullscreen = function () {
  if (document.documentElement.requestFullscreen) {
    document.documentElement.requestFullscreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  } else if (document.documentElement.webkitRequestFullscreen) {
    document.documentElement.webkitRequestFullscreen();
  } else if (document.documentElement.msRequestFullscreen) {
    document.documentElement.msRequestFullscreen();
  }
}
export const tools = function () {
  //判断对象是否为空
  function pri_isNull(obj) {
    var pri_obj = obj || '';
    if (pri_obj === '') {
      return true;
    } else {
      return false;
    }
  }
  return {
    /**
     * 判断对象是否为空
     * @param obj:对象
     * @returns {boolean}
     */
    isNull: function isNull(obj) {
      return pri_isNull(obj);
    },
    isNotNull: function isNotNull(obj) {
      return !pri_isNull(obj);
    },
    listNotEmpty: function (list) {
      if (list && list.length > 0) {
        return true;
      }
      return false;
    },
    replaceAll: function (str, s1, s2) {
      return str.replace(new RegExp(s1, "gm"), s2);
    },
    getBytesLength: function (str) {
      // 在GBK编码里，除了ASCII字符，其它都占两个字符宽
      return str.replace(/[^\x00-\xff]/g, 'xx').length;
    },
    /**
     * 判断对象是不是一个function
     * @param obj
     * @returns {boolean}
     */
    isFunction: function isFunction(obj) {
      return typeof obj === 'function';
    },

    /**
     * 判断对象是不是一个function
     * @param obj
     * @returns {boolean}
     */
    isString: function isString(obj) {
      return typeof obj === 'string';
    },

    /**
     * 判断对象是不是一个function
     * @param obj
     * @returns {boolean}
     */
    isNumber: function isNumber(obj) {
      return typeof obj === 'number';
    },

    /**
     * 打印显示一个对象所有的属性和方法
     * @param msg
     */
    log: function log(msg) {
      console.dir(msg);
    },

    /**
     * 获得当前地址的参数信息
     * @param name:string
     * @returns {info}
     */
    getParam: function getParam(name) {
      var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
      if (tools.isNUll(result) || result.length < 1) {
        return "";
      }
      return result[1];
    },
    isWeiXinMini: function () {
      var _isWeiXinMini = window.__wxjs_environment === 'miniprogram';
      return _isWeiXinMini;
    },
    /**
     * 去除空字符串
     * @param str 来源字符串
     * @param is_global 是否去除中间的空格
     * @returns {string|XML|void|*}
     */
    trim: function trim(str, is_global) {
      var result = void 0;
      result = str.replace(/(^\s+)|(\s+$)/g, "");
      if (is_global) {
        result = result.replace(/\s/g, "");
      }
      return result;
    },

    /**
     * 多行合并成一行
     * @returns {XML|string|void|*}
     */
    newLine: function newLine(str) {
      var result = void 0;
      result = str.replace(/(\n)+|(\r\n)+/g, "");
      return result;
    },
    encrypt: function encrypt(message, key) {
      var keyHex = CryptoJS.enc.Utf8.parse(key);
      var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      });
      return encrypted.toString();
    },
    decrypt: function decrypt(ciphertext, key) {
      var keyHex = CryptoJS.enc.Utf8.parse(key);
      // direct decrypt ciphertext
      var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
      }, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      });
      return decrypted.toString(CryptoJS.enc.Utf8);
    },

    /**
     * 判断是不是微信
     * @returns {boolean}
     */
    isWeiXin: function isWeiXin() {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
      } else {
        return false;
      }
    },

    /**
     * 判断是ios还是android
     * @return {*}
     */
    version: function version() {
      if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        //判断iPhone|iPad|iPod|iOS
        //alert(navigator.userAgent);
        return "iOS";
      } else if (/(Android)/i.test(navigator.userAgent)) {
        //判断Android
        return "android"; //alert(navigator.userAgent);
      } else {
        //pc
        return "android";
      }
    },
    /**
     * 将日期字符串转成标准Date日期
     * @returns {Date}
     */
    getDate: function getDate(strDate) {
      strDate = strDate.replace(/-/g, "/");
      return new Date(strDate);
    },
    toDateStr: function toDateStr(strDate) {
      strDate = strDate.replace(/\//g, "-");
      return strDate;
    },
    toStrDay: function (index) {
      var weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      var week = weeks[index - 1];
      return week;
    },

    /**
     * 日期对象转化成毫秒数
     * @param date
     * @returns {number}
     */
    dateToLong: function dateToLong(date) {
      return date.getTime();
    },

    /**
     * 毫秒转换成日期对象
     * @param dateVal (number) 日期的毫秒数
     * @returns {Date}
     */
    longToDate: function longToDate(dateVal) {
      return new Date(dateVal);
    },

    /**
     * 获取对象的唯一标识符
     * @returns {string}
     */
    uniqueId: function uniqueId() {
      var ramdomLength = 11;
      return Number(Math.random().toString().substr(3, ramdomLength) + Date.now()).toString(36);
    },

    /**
     * 随机数时间戳
     * @return {string}
     */
    randomTime: function randomTime() {
      var a = Math.random,
        b = parseInt;
      return Number(new Date()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a());
    },

    /**
     * 计算两数乘积（解决精度丢失）
     * @param arg1  乘数1
     * @param arg2  乘数2
     * @return {number} 积
     */
    accMul: function accMul(arg1, arg2) {
      var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {}
      try {
        m += s2.split(".")[1].length;
      } catch (e) {}
      return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },

    /**
     * 将字符串作为URI组件进行编码
     * 只对文字进行编码,数字和特殊字符以及字母不编码
     * @param str
     * @returns {string}
     */
    strEncode: function strEncode(str) {
      return encodeURIComponent(str);
    },

    /**
     * 字符串解码
     * @param str
     * @returns {string}
     */
    strDencode: function strDencode(str) {
      return decodeURIComponent(str);
    },

    /**
     * 获取域名主机
     * @param url:域名
     * @returns {string}
     */
    getHost: function getHost(url) {
      var host = "null";
      if (tools.isNUll(url)) {
        url = window.location.href;
      }
      var regex = /^\w+\:\/\/([^\/]*).*/;
      var match = url.match(regex);
      if (tools.isNotNull(match)) {
        host = match[1];
      }
      return host;
    },
    /**
     * 获得当前路径
     * @return {string}
     */
    getCurrentPageUrl: function getCurrentPageUrl() {
      var currentPageUrl = "";
      if (typeof this.href === "undefined") {
        currentPageUrl = document.location.toString().toLowerCase();
      } else {
        currentPageUrl = this.href.toString().toLowerCase();
      }
      return currentPageUrl;
    },

    /**
     * 判断是否移动设备访问
     * @return {boolean}
     */
    isMobileUserAgent: function isMobileUserAgent() {
      return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
    },

    /**
     * 判断是否苹果移动设备访问
     * @return {boolean}
     */
    isAppleMobileDevice: function isAppleMobileDevice() {
      return (/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()));
    },

    /**
     * 判断是否安卓移动设备访问
     * @return {boolean}
     */
    isAndroidMobileDevice: function isAndroidMobileDevice() {
      return (/android/i.test(navigator.userAgent.toLowerCase()));
    },

    /**
     * 判断是否为touch屏幕
     * @return {boolean|*}
     */
    isTouchScreen: function isTouchScreen() {
      return 'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch;
    },

    /**
     * 判断是否在安卓上的谷歌浏览器
     * @return {boolean}
     */
    isNewChromeOnAndroid: function isNewChromeOnAndroid() {
      if (this.isAndroidMobileDevice()) {
        var userAgent = navigator.userAgent.toLowerCase();
        if (/chrome/i.test(userAgent)) {
          var parts = userAgent.split('chrome/');

          var fullVersionString = parts[1].split(" ")[0];
          var versionString = fullVersionString.split('.')[0];
          var version = parseInt(versionString);

          if (version >= 27) {
            return true;
          }
        }
      }
      return false;
    },

    /**
     * 阻止冒泡
     * @param e
     */
    stopBubble: function stopBubble(e) {
      e = e || window.event;
      if (e.stopPropagation) {
        e.stopPropagation(); //W3C阻止冒泡方法
      } else {
        e.cancelBubble = true; //IE阻止冒泡方法
      }
    },

    /**
     * 获得浏览器url中的参数值
     * @param name
     * @return {string|null}
     */
    getUrlParam: function getUrlParam(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
    },

    /**
     * 深度拷贝对象
     * @param obj
     * @return {*}
     */
    cloneObj: function cloneObj(obj) {
      var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf());
      for (var key in obj) {
        if (o[key] != obj[key]) {
          if (_typeof(obj[key]) == 'object') {
            o[key] = mods.cloneObj(obj[key]);
          } else {
            o[key] = obj[key];
          }
        }
      }
      return o;
    },

    /**
     * 数组去重
     * @param arr
     * @return {Array}
     */
    unique: function unique(arr) {
      var result = [],
        json = {};
      for (var i = 0, len = arr.length; i < len; i++) {
        if (!json[arr[i]]) {
          json[arr[i]] = 1;
          result.push(arr[i]); //返回没被删除的元素
        }
      }
      return result;
    },

    /**
     * 判断数组元素是否重复
     * @return {boolean}
     */
    isRepeat: function isRepeat(arr) {
      var hash = {};
      for (var i in arr) {
        if (hash[arr[i]]) return true;
        hash[arr[i]] = true;
      }
      return false;
    },

    /**
     * 生成随机数
     * @param min
     * @param max
     * @return {*}
     */
    randombetween: function randombetween(min, max) {
      return min + Math.random() * (max - min + 1);
    },

    /**
     * 计算字符串的真正长度
     * String有个属性length，但是它不能区分英文字符，
     * 计算中文字符和全角字符。但是在数据存储的时候中文和全角都是用两个字节来存储的，
     * @param str
     * @return {number}
     */
    codeLength: function codeLength(str) {
      var len = 0;
      if (this == null || this.length == 0) return 0;
      var string = str.replace(/(^\s*)|(\s*$)/g, ""); //去掉空格
      for (var i = 0; i < string.length; i++) {
        if (string.charCodeAt(i) > 0 && string.charCodeAt(i) < 128) len++;
        else len += 2;
      }
      return len;
    },

    /**
     * 判断电子邮件是否符合规范
     * @param string
     * @return {boolean}
     */
    emailcheck: function emailcheck(string) {
      var re;
      re = new RegExp("^[\\w-_\\.]+@([a-z|0-9|-]+\\.)+[a-z]{2,5}$");
      return re.test(string.toLowerCase());
    },

    /**
     * 根据年和月取当月的最后一天(也就是当月有多少天)
     * @param year
     * @param month
     * @return {number}
     */
    getLastDay: function getLastDay(year, month) {
      //取年
      var new_year = year;
      //取到下一个月的第一天,注意这里传入的month是从1～12
      var new_month = month++;
      //如果当前是12月，则转至下一年
      if (month > 12) {
        new_month -= 12;
        new_year++;
      }
      var new_date = new Date(new_year, new_month, 1);
      return new Date(new_date.getTime() - 1000 * 60 * 60 * 24).getDate();
    },

    /**
     * 创建用于ajax技术的 XMLHttpRequest对象。
     * 用法：
     * try{
     * createXMLHttpRequest();
     * xmlHttp_siteTotal.open("POST", url);
     * xmlHttp_siteTotal.send(xml);
     * }catch(e) {
     * }
     */
    createXMLHttpRequest: function createXMLHttpRequest() {
      var xmlHttp_siteTotal;
      if (window.XMLHttpRequest) {
        xmlHttp_siteTotal = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        xmlHttp_siteTotal = new ActiveXObject("Microsoft.XMLHTTP");
      }
    },

    /**
     * 将图片src转成data64
     * @param img
     * @return {string}
     */
    createImgData: function createImgData(img) {
      var image = new Image();
      image.src = img.src || img;
      var tmpCanvas = $("<canvas></canvas>")[0];
      var tmpCtx = tmpCanvas.getContext("2d");
      if (tmpCanvas) {
        tmpCanvas.width = image.width;
        tmpCanvas.height = image.height;
        tmpCtx.drawImage(image, 0, 0);
        return tmpCanvas.toDataURL();
      }
    },
    getLocation: function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (p) {
          callback(p.coords.latitude, p.coords.longitude);
        }, function (e) {
          var msg = e.code + "\n" + e.message;
        });
      }
    },

    /**
     * 获取网页参数
     * @param name
     * @return {null}
     */
    getQueryString: function getQueryString(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    },
    getKeyValue: function (searchStr, key) {
      /*var pattent = new RegExp(`(?:^${key}|;${key})=([^;]*);?`);
       pattent.exec(searchStr);*/
      return RegExp.$1;
    },
    /**
     * 是否还有下页数据
     * @param list
     * @param pageSize
     * @returns {boolean}
     */
    isNextPage: function isNextPage(list, pageSize) {
      var page = 10;
      if (tools.isNotNull(pageSize)) {
        page = pageSize;
      }
      if (tools.isNotNull(list) && list.length == page) {
        return true;
      }
      return false;
    },
    /**
     * 把时间转化成字符串
     * @param inputTime
     * @return {string}
     */
    formatDateTime: function formatDateTime(inputTime, isShort) {
      var date = new Date(inputTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      s;
      m = m < 10 ? '0' + m : m;
      var d = date.getDate();
      d = d < 10 ? '0' + d : d;
      var h = date.getHours();
      h = h < 10 ? '0' + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? '0' + minute : minute;
      second = second < 10 ? '0' + second : second;
      if (isShort) {
        return y + '-' + m + '-' + d;
      } else {
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
      }
    },
    formatDateHour: function (inputTime) {
      var date = new Date(inputTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? '0' + m : m;
      var d = date.getDate();
      d = d < 10 ? '0' + d : d;
      var h = date.getHours();
      h = h < 10 ? '0' + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? '0' + minute : minute;
      second = second < 10 ? '0' + second : second;
      return h + ':' + minute;
    },
    /**
     * 把file this.files[0]  转化成可以用url blob
     * @param file
     * @return {*}
     */
    getObjectURL: function (file) {
      var url = null;
      if (tools.isNotNull(window.createObjectURL)) { // basic
        url = window.createObjectURL(file);
      } else if (tools.isNotNull(window.URL)) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (tools.isNotNull(window.webkitURL)) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },
    newline: function newline(str) {
      var result;
      result = str.replace(/(\n)+|(\r\n)+/g, "");
      return result;
    },
    getUrlParam: function (paraName) {
      var url = document.location.toString();
      var arrObj = url.split("?");

      if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;

        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split("=");

          if (arr != null && arr[0] == paraName) {
            return arr[1];
          }
        }
        return "";
      } else {
        return "";
      }
    },
    formatSecond: function (timer) {
      var h1 = timer % 3600;
      var m = Math.floor(h1 / 60);
      var m1 = h1 % 60;
      if (m < 10) {
        m = "0" + m;
      }
      if (m1 < 10) {
        m1 = "0" + m1;
      }
      return m.toString() + ":" + m1.toString()
    },
    pageName: function () {
      var a = window.location.href;
      var b = a.split("/");
      var c = b.slice(b.length - 1, b.length).toString(String).split(".");
      return c[0];
    }
  }
}();
